<?php

namespace frontend\modules\demo\controllers;

use common\models\Article;
use yii\web\Controller;
use Yii;
/**
 * Default controller for the `demo` module
 */
class CacheController extends Controller
{
    /**
     * Renders the index view for the module
     * @return string
     */
    public function actionIndex()
    {
        //默认cache设置
        $cache= Yii::$app->cache;
        //$cache->flush();
        $db= Yii::$app->db;
        $article = Article::find()->cache(3600)->all();
        $customer = $db->createCommand('SELECT * FROM article WHERE id=1')->cache(60)->queryOne();

        $dependency = new \yii\caching\DbDependency(['sql'=>'SELECT COUNT(*) FROM article']);

        $key='test';
        $data = $cache->getOrSet($key, function () {
            return 44444;
        },3600,$dependency);

        print_r($data);






        // setting multiple cache keys to store data forever and tagging them with "user-123"
        Yii::$app->cache->set('user_42_profile', '', 0, new TagDependency(['tags' => 'user-123']));
        Yii::$app->cache->set('user_42_stats', '', 0, new TagDependency(['tags' => 'user-123']));

// invalidating all keys tagged with "user-123"
        TagDependency::invalidate(Yii::$app->cache, 'user-123');





        $cache = Yii::$app->cache;
        $fileDependency = new \yii\caching\FileDependency(['fileName'=>'@app/hello.txt']);
        $sqlDependency = new \yii\caching\DbDependency(['sql'=>'SELECT COUNT(*) FROM category']);

        $cache->set('abc', 'hello yii', 3000, new ChainedDependency([
            'dependOnAll'=>true,
            'dependencies' => [$fileDependency, $sqlDependency]
        ]));







        $dependency = new \yii\caching\FileDependency(['fileName'=>'@app/hello.txt']);
        $cache->add("hy","Hello Yii",3000,$dependency);


        $dependency = new \yii\caching\ExpressionDependency(['expression'=>'\Yii::$app->request->get("id")']);
        $cache->add("hy","Hello Yii",3000,$dependency);
    }
}
